﻿using Common;
using FCT551.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace FCT551.Helper
{
    /// <summary>
    /// 文件写入帮助类
    /// </summary>
    public static class FileWriteHelper
    {
        private static string AllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "测试报告");

        /// <summary>
        /// 写入txt文件
        /// </summary>
        /// <param name="list"></param>
        /// <param name="delimiter"></param>
        public static void WriteToFile(List<NewWorkStationModel> list, string name)
        {
            try
            {
                if (list == null || list.Count == 0)
                    return;

                FileIsExit();
                string time1 = DateTime.Now.ToString("yyyy-MM-dd");

                string filePath = Path.Combine(AllPath, time1, name + ".txt");
                if (!File.Exists(filePath))
                {
                    File.Create(filePath).Close();
                }

                using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 65536);
                using var writer = new StreamWriter(fileStream, Encoding.UTF8, 65536);
                // 批量写入数据行
                foreach (var item in list)
                {
                    string writeMsg = item.Code + "," + item.StationTestRes.ToString() + "," + item.Result + "," + item.Name + ";";

                    writer.Write(writeMsg);
                    writer.WriteLine();
                }
            }
            catch (Exception e)
            {
                MyLog.Error(e);
            }
        }

        /// <summary>
        /// 电压电流结果写入csv文件
        /// </summary>
        /// <param name="list"></param>
        /// <param name="delimiter"></param>
        public static void WriteToCsv(Dictionary<string, List<double>> keyValuePairs, string name)
        {
            try
            {
                if (keyValuePairs == null || keyValuePairs.Count == 0)
                    return;

                FileIsExit();
                string time1 = DateTime.Now.ToString("yyyy-MM-dd");

                string filePath = System.IO.Path.Combine(AllPath, time1, name + ".csv");
                if (!File.Exists(filePath))
                {
                    File.Create(filePath).Close();
                }

                //写入

                using (var writer = new StreamWriter(filePath))
                {
                    // 写入表头（Key作为列名）
                    writer.WriteLine(string.Join(",", keyValuePairs.Keys));

                    // 获取最大行数
                    int maxRows = keyValuePairs.Values.Max(list => list?.Count ?? 0);

                    // 逐行写入数据
                    for (int row = 0; row < maxRows; row++)
                    {
                        var line = new List<string>();
                        foreach (var key in keyValuePairs.Keys)
                        {
                            var value = keyValuePairs[key]?.Count > row ? keyValuePairs[key][row].ToString() : "";
                            line.Add(value);
                        }
                        writer.WriteLine(string.Join(",", line));
                    }
                }
            }
            catch (Exception e)
            {
                MyLog.Error(e);
            }
        }

        private static bool NeedEscape(string value, string delimiter)
        {
            return !string.IsNullOrEmpty(value) &&
                   (value.Contains(delimiter) || value.Contains("\"") ||
                    value.Contains("\n") || value.Contains("\r"));
        }

        public static void FileIsExit()
        {
            // 确保目录存在

            if (!string.IsNullOrEmpty(AllPath) && !Directory.Exists(AllPath))
            {
                Directory.CreateDirectory(AllPath);
            }

            string path = Path.Combine(AllPath, DateTime.Now.ToString("yyyy-MM-dd"));
            if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
    }
}